var map, ml, pml,nml;
$(function() {
    var bh = $("body").height();
    $("#allmap").height(parseInt(bh) - 45);
    initMap(); //创建和初始化地图  

})

//创建和初始化地图函数：  
function initMap() {
    createMap(); //创建地图  
    setMapEvent(); //设置地图事件  
    addMapControl(); //向地图添加控件 
    //鼠标单击事件函数  
    // function showInfo(e){  
    //     // window.location.href="http://www.baidu.com";  
    // }  

    //鼠标单击事件  
    // map.addEventListener("click", showInfo);  

    // 拖拽过程
    map.addEventListener("dragging", function() {
        $('#address').text('正在获取地理位置...');
    })

    // 缩放级别改变之后
    map.addEventListener("zoomend", function() {
        relaod_map();
    })
    // 地图移动完成后的事件
    map.addEventListener("moveend", function() {
        relaod_map();
    });
}

//创建地图函数：  
function createMap() {
    map = new BMap.Map("allmap"); //在百度地图容器中创建一个地图  
    if (localStorage.lng != '' && localStorage.lat != '') {
        var point = new BMap.Point(localStorage.lng, localStorage.lat); //定义一个中心点坐标  
        map.centerAndZoom(point, 17); //设定地图的中心点和坐标并将地图显示在地图容器中
        window.map = map; //将map变量存储在全局  
        relaod_map(point);
    } else {
        var point = new BMap.Point(103.833724, 36.065339); //定义一个中心点坐标 
        map.centerAndZoom(point, 17); //设定地图的中心点和坐标并将地图显示在地图容器中
        window.map = map; //将map变量存储在全局   
        getlocation();
    }


}

//搜索
function ssss(msg) {
	var options = {
		onSearchComplete: function(results){
			// 判断状态是否正确
			if (local.getStatus() == BMAP_STATUS_SUCCESS){
				var s = [];
				for (var i = 0; i < results.getCurrentNumPois(); i ++){
					s.push(results.getPoi(i).title + ", " + results.getPoi(i).address);
				}
			}
			console.log(s);
		}
	};
	var local = new BMap.LocalSearch(map, options);
	local.searchNearby(msg,nml,1000);
}

//定位
function getlocation() {
    var geolocation = new BMap.Geolocation();
    geolocation.getCurrentPosition(function(r) {
        if (this.getStatus() == BMAP_STATUS_SUCCESS) {
            var mk = new BMap.Marker(r.point);
            map.addOverlay(mk);
            map.panTo(r.point);
            ml = r.point;
            relaod_map(r.point);
        } else {
            alert('failed' + this.getStatus());
        }
    }, { enableHighAccuracy: true })
}

//地图事件设置函数：  
function setMapEvent() {
    map.enableDragging(); //启用地图拖拽事件，默认启用(可不写)  
    map.enableScrollWheelZoom(); //启用地图滚轮放大缩小  
    map.enableDoubleClickZoom(); //启用鼠标双击放大，默认启用(可不写)  
    map.enableKeyboard(); //启用键盘上下左右键移动地图  
}

//地图控件添加函数：  
function addMapControl() {
    //向地图中添加缩放控件  
    var ctrl_nav = new BMap.NavigationControl({ anchor: BMAP_ANCHOR_TOP_LEFT, type: BMAP_NAVIGATION_CONTROL_LARGE });
    map.addControl(ctrl_nav);

    //向地图中添加比例尺控件  
    var ctrl_sca = new BMap.ScaleControl({ anchor: BMAP_ANCHOR_BOTTOM_LEFT });
    map.addControl(ctrl_sca);
}


function relaod_map(point) {
    map.clearOverlays();
    if (!point) {
        var center = map.getCenter();
    } else {
        center = point;
    }
    nml = center;
    localStorage.mllng = center.lng;
    localStorage.mllat = center.lat;
    var marker = new BMap.Marker(center); // 创建标注  
    map.addOverlay(marker);
    var opts = {
        position: center, // 指定文本标注所在的地理位置
        offset: new BMap.Size(-26, -45) //设置文本偏移量
    }
    var label = new BMap.Label("送到这里", opts); // 创建文本标注对象
    label.setStyle({
        color: "gray",
        fontSize: "12px",
        height: "20px",
        lineHeight: "18px",
        fontFamily: "微软雅黑",
        borderColor: "#90ca3d",
        borderRadius: "5px"
    });
    map.addOverlay(label);

    // 获取地理信息
    var geoc = new BMap.Geocoder();
    geoc.getLocation(center, function(rs) {
        pml = rs;
        console.log(rs);
        var addComp = rs.addressComponents;
        var province = addComp.province;
        var city = addComp.city;
        var district = addComp.district;
        var street = addComp.street;
        var streetNumber = addComp.streetNumber;
        // 显示最佳匹配区域名
        if (rs.surroundingPois.length) {
            var bestInfo = rs.surroundingPois[0];
            $('#address').text(bestInfo.title);

            $('.address-info').click(function() {
                getlist();
            });
        } else {
            $('#address').text('该位置暂无信息');
        }

        //显示街道
        if (street == '' && streetNumber == '') {
            $('#street').text('该位置暂无街道信息');
        } else {
            $('#street').text(street + streetNumber);
        }

    });
}

//返回定位
function breaklm() {
    map.addOverlay(ml);
    map.panTo(ml);
}


function showmsg(msg) {
    mui.toast(msg, { duration: 'short', type: 'div' })
}

//确定提交
function postdata() {
    if (pml) {
        if (localStorage.address) { $("#cityArea").text(localStorage.address); }
        if (localStorage.lnt) { $("#lnt").val(localStorage.lnt); }
        if (localStorage.lat) { $("#lat").val(localStorage.lat); }
        localStorage.address = pml['addressComponents']['province'] + pml['addressComponents']['city'] + pml['addressComponents']['district'];
        if (pml['surroundingPois'].length > 0) {
            localStorage.address += pml['surroundingPois'][0]['title'];
        }

        localStorage.lng = pml['point']['lng'];
        localStorage.lat = pml['point']['lat'];

        if (pml['addressComponents']['street']) {
            localStorage.number = pml['addressComponents']['street'] + pml['addressComponents']['streetNumber'];
        }
    }
    // console.log(history.go());
    // history.go(-1);
    // window.history.back();
    window.location.href = localStorage.ret;
}

function getlist() {
    localStorage.pml = pml;
    window.location.href = "/Wx/Address/mapList";
}